<?php
 include "counter2.php";

pagestart();

// parameters
$place = $counter->get_input("place", "place", "get");
$find = $counter->get_input("find", "", "post");

function locate_place($sql, $placeid) {

	global $find;
	global $find_like;
	global $place_rows;

print "<!-- $sql -->\n";
 	$placeq = mysql_query($sql);
	if ( $place_rows = mysql_num_rows($placeq) ) {
 		$place = mysql_fetch_array($placeq);
	 	while ( $place['type'] == "alias" ) {
 		 	$placeq = mysql_query("select * from places where ".
				 	"f_key = '". $place['within']."'");
 		 	$place = mysql_fetch_array($placeq);
	 	}
	}
	if ( !$find && $place_rows > 1 ) {
		$find = ereg_replace(".*:", "", $placeid);
	}
print "<!-- sql found = $place_rows rows -->\n";
	return $place;
}


 if (!$columns) {
    $columns = 3;
 }
 if (!$place) {
    $place = "All";
 }
$find_like = "=";
 if ( $find ) {
        # Check if a very narrow search had exactly one result.
        # In that case, go straight there.
	$findq = mysql_query("select * from places where name like '%:$find' or name = '$find' or longname = '$find'");
	if ( mysql_num_rows($findq) == 1 ) {
		  $found = mysql_fetch_array($findq);   
		while ( $found['type'] == "alias" ) {
			$findq =  mysql_query("select * from places where f_key = '".$found['within']."'"); 
			 $found = mysql_fetch_array($findq);
		}
		$place=$found['name'];
		$find="";
	}
}

	$place_hold = $place;
 	$placeq = "select * from places where name = '$place'";
	$place_res = locate_place($placeq, $place);
	if ( ! $place_res) {
		$place_new = ereg_replace(":.*:", ":%:", $place);
 		$placeq = "select * from places where name like '$place_new'";
 		$place_res = locate_place($placeq, $place_new);
	}
	if ( ! $place_res) {
		list ($country, $state, $city) = split(":", $place);
 		$placeq = "select * from places where name = '$country:$state'";
 		$place_res = locate_place($placeq, "$country:$state");
	}
	if ( ! $place_res) {
 		$placeq = "select * from places where name like '%:$state:$city'";
 		$place_res = locate_place($placeq, $city);
	}
	if ( ! $place_res) {
 		$placeq = "select * from places where name like '%:$state'";
 		$place_res = locate_place($placeq, $state);
		if (  $place_res) {
			$cc = ereg_replace(":.*", "", $place_res['name']);
			$placeq = "select * from places where name = '$cc::$city'";
			$place_res = locate_place($placeq, $state);
		}
	}
	if ( ! $place_res) {  
 		$placeq = "select * from places where name = '$country'";
 		$place_res = locate_place($placeq, $county);
	}
	if ( ! $place_res ) {
		if ( ! $find ) {
			$find = $city;
		}
		$placeq = "select * from places where name = 'all'";
                $place_res = locate_place($placeq, "All"); 
	}
	$place = $place_res;

     
function page_bar($personcount, $quotedname) {
 global $PHP_SELF;
 if ( $personcount > 90 ) {
        $page_no = 0;
        while ( ( $page_no * 90 ) < $personcount ) {
                if ( ! $page_no ) {
                        print "[ <a href=\"" . $PHP_SELF . "?place=$quotedname\">"._("First")."</a>";
                } else if ( (($page_no * 90 ) + 90) > $personcount ) {
                        print " | <a href=\"" . $PHP_SELF . "?place=$quotedname&page=$page_no\">"._("Last")."</a> ]";
                } else {
                        print " | <a href=\"" . $PHP_SELF . "?place=$quotedname&page=".
                                $page_no."\">"._("Page")." ".($page_no + 1)."</a>";
                }
                $page_no++;
        }
      }
}

print "<html>";
pagehead(_("Information about") . " " . $place['longname']);
print "\n<BODY bgcolor=\"white\">\n";
pagetop();
print "\n<table>" .
"\n<tr><th>" . _("Search for a place") . "</th>\n<td><form action=" . $PHP_SELF . " method=post>" .
"\n<input type=text name=find size=20>" .
"\n<input type=submit value=\"" . _("Go") . "\">" .
"\n</form></td>\n</tr>" .
"\n</table>";

 if ( $find ) {
        # note: this search is wider than the one further up the page.
        # so it's possible to find more here.
	$findq =  mysql_query("select * from places where name like '%$find%' or longname like '%$find%' order by name");
	if ( mysql_num_rows($findq) > 1 ) {
		print "\n<table>\n<tr><th align=left>" . _("Search results for ") . $find;
		while ( $found = mysql_fetch_array($findq) ) {
			print "\n<tr><td>";
			place_bar ($found, 1);
			print "</td></tr>";
		}   
		print "\n</table>";	
	} else { 
		print _("Search results") . "\n<br>\n" . _("Nothing found for ") . $find;
	}
}

print "\n<h1><img src=\"/gifs/Logo-small.png\" alt=\"" . _("Linux Counter Logo") . "\">" . _("Linux users in") . " " . $place['longname'] . "</h1>";
place_bar($place);
print "\n<br>\n";

 $lowname = strtolower($place['name']);
 if (file_exists($homedir . "/www/bycountry/$lowname.png")) {
      echo "<img src=\"/bycountry/$lowname.png\"><p>\n";
 } else {
    echo "<img src=\"/tempplots/" . $place['name'] . ".png\"><p>\n";
}

print "\n<font size=-2><a href=\"/legal.php\">" . _("Copyright &copy; Linux Counter Project. Usage restricted") . "</a></font>\n<br>\n";
 
 $place_html = ereg_replace(".*html:", "", $place['f_clean']);
 if (  $place_html != $place['f_clean'] ) {
 	print "$place_html\n<br clear=all>";
 }

print "\n<table border=0 width=\"80%\">" .
"\n<tr><td>" .
"\n<table>" .
"\n<tr><th align=right>" . _("Place code") . ":</th>\n<td>" . $place['name'] . "</td></tr>" .
"\n<tr><th align=right>" . _("Maintainer(s)") . ":</th><td>" . findmaintainer($place) . "</td></tr>" .
"\n<tr><th align=right>" . _("Population") . ":</th><td>" . $place['population'] . " " . _(" million") . "</td></tr>" .
"\n<tr><th align=right>" . _("Hostcount") . ":</th><td>" . $place['hostcount'] . "</td></tr>" .
"\n<tr><th align=right>" . _("Linux users") . ":</th><td>" . $place['users'] . "</td></tr>";

if ($place['population'] > 0) {
   $density = $place['users'] / $place['population'];
//   print "<tr><td>DEBUG: ". $place['population'] . " " . $place['users'] . " " . $density; 
   printf("\n<tr><th align=right>" . _("Linux density") . ":</th><td>%5.2f " . _("users/million") . "</td></tr>", $place['users'] / $place['population']);
}

// print "<tr><td>DEBUG: " . $place['population'] . " " . $place['users'] . " " . $density; 

if ($place['hostcount'] > 0) {
    printf("\n<tr><th align=right>" . _("Linux users per 1000 IP hosts") . ":</th><td>%5.2f</td></tr>",
	$place['users'] * 1000/ $place['hostcount']);
}

print "\n</table>\n<p>\n";
if ($place['type'] == "country" && $place['users'] > 0) {
   $tq = mysql_query("select * from temp_short where country = '".
							$place['name']."'");
   $td = mysql_fetch_array($tq);
   printf (_("%s is no. %s in the density statistics, with %s users/Mpop") . "\n<br>\n",
   		$place['longname'], 
		$td['rank'], 
		$td['userdensity']);
   // print $place['longname']." is no. ".$td['rank']." in the density statistics, with ".$td['userdensity']." users/Mpop<br>\n";
   if ($td['rank'] > 1) {
      $tq = mysql_query("select * from temp_short where rank = " . ($td['rank'] - 1));
   if ($tq == 0) {
       print("\n</table>" . _("MySQL error") . ": " . mysql_errno() . ":" . mysql_error());
       die("Query for count failed");
    }                                                                                                          
      $tdup = mysql_fetch_array($tq);
      $need = $tdup['userdensity'] * $td['population'] - $td['users'] + 1;
      printf(_("%s needs %d more users to pass %s and become no. %d") . "\n<br>\n",
              $place['longname'],
	      $need, placeurl($tdup['country'], $tdup['name']), $td['rank'] - 1);
   }
   $tq = mysql_query("select * from temp_short where rank = " . ($td['rank'] + 1));
   if (mysql_num_rows($tq) > 0) {
      $tdown = mysql_fetch_array($tq);
      $need = $td['userdensity'] * $tdown['population'] - $tdown['users'] + 1;
      printf(_("%s needs %d more users to pass %s and become no. %d") . "\n<br>\n",
	      placeurl($tdown['country'], $tdown['name']), $need, $td['name'], $td['rank']);
   }
} 
if ($place['within'] != 0) {
   $uq = mysql_query("select * from places where f_key = " . $place['within']);
   $upper = mysql_fetch_array($uq);
//   printf("$place['longname'] is part of %s<br>\n", placeurl($upper['name'], $upper['longname']));
}

print "\n</table>\n" .

"\n<!-- Subordinate places -->";

function uindex ($personcount, $place, $quotedplace) {

 global $PHP_SELF;  
	if ( $personcount < 91 ) {
		return;
	}
	$alphaq = mysql_query(
           "select substring(name, 1, 1) as c from persons where placeid = '$quotedplace' and may_publish = 'YES' group by c");
	print "\n<h4>";
        while ($alpha = mysql_fetch_row($alphaq)) {
            $a = strtoupper($alpha['0']);
	    if ( $a >= "A" && $a <= "Z" ) {
	    	print "\n<a href=\"$PHP_SELF?start=$a&place=".
			urlencode($quotedplace).
			"#person\">$a</a> &nbsp; ";
	    }
        }
        print "\n</h4>\n<p>\n";
}

function presentlist($type, $title) {

   global $PHP_SELF;
   global $place;
   global $columns;

   $col = floor($columns/2);
   if ($col == 0) { $col = 1; }

   $places = mysql_query("select * from places where within = ".
			$place['f_key'].
			" and type = '$type' and users > 0 order by longname");
   if (mysql_num_rows($places) == 0) { return; }
   print "\n<h2>$title " . _("within") . " " . $place['longname']."</h2>\n";
   if (mysql_num_rows($places) > 20) {
	$alphaq = mysql_query(
           "select substring(longname, 1, 1) as c from places where within = ". $place['f_key'].  " and type = '$type' and users > 0 group by c");
	print "\n<h4>";
	$expect = "A";
	$previous = "@";
        while ($alpha = mysql_fetch_row($alphaq)) {
            $a = strtoupper($alpha['0']);
	    if ( $a > "Z" ) {
	    	$previous++;
		$a = $previous;
 	    }
	    print "\n<a href=\"#place_".$type."_$a\">$a</a> &nbsp; ";
	    $previous = $a;
        }
        print "\n</h4>\n<p>\n";
   }
   print "\n<table>";
   $preva = "";
   print "\n<tr>";
   for ($itemcount=0; $itemcount <= $col; $itemcount += 2) {
	print "\n<th align=left>" . _("Name") . "</th><th>" . _("Users") . "</th>";
   }
   print "\n</tr>\n";
   $itemcount = 0;
   while ($sub = mysql_fetch_array($places)) {
       $placeurl = urlencode($sub['name']);
       $a = strtoupper(substr($sub['longname'], 0, 1));
       if ($itemcount % $col == 0) {
 	  print "<tr>";
       }
       ++ $itemcount;
       print "<td>";
       if ( $a > "Z" ) {
		$a = $preva;
       }
       if ($a > $preva) {
	   print "<a name=\"place_".$type."_$a\"> </a>";
           $preva = $a;
       }
       print "<a href=\"$PHP_SELF?place=$placeurl\">".$sub['longname']."</a></td>";
       print "\n<td align=right>".$sub['users']."</td></tr>\n";
   }
   print "</table>\n";
}

  presentlist("country", "Countries");
  presentlist("state", "States/Regions");
  presentlist("city", "Cities");

print "\n<!-- Subordinate persons -->\n";

if  ( $people != "no" ) {
  $quotedname = mysql_escape_string($place['name']);
  $totalcount   = dbcount("persons", "placeid = '$quotedname'");
  $privatecount = dbcount("persons",
			"placeid = '$quotedname' and  may_publish = 'NO'");
  $personcount  = dbcount("persons",
			"placeid = '$quotedname' and  may_publish = 'YES'");
  if ($personcount > 90) {
      $start_after = urldecode($next);
      if ($page) {
	$start=$page*90;
	$end = $start + 90;
	if ( $end > $personcount ) {
		$end = $personcount;
	}
      $note = "Listing users $start to $end of $personcount registered persons.";
      $persons = mysql_query("select * from persons where placeid = '$quotedname' and may_publish = 'YES' order by name limit $start,90");
      } elseif ($start)  {
//      $note = "Listing the first 90 of $personcount registered persons.";
      $persons = mysql_query("select * from persons where placeid = '$quotedname' and name >= '$start' and may_publish = 'YES' order by name limit 90");
      } else {
	 $note = "Listing the first 90 of $personcount registered persons.";
      $persons = mysql_query("select * from persons where placeid = '$quotedname' and may_publish = 'YES' order by name limit 90");
      }
  } else {
      $note = "Listing $personcount registered persons.";
      $persons = mysql_query("select * from persons where placeid = '$quotedname' and may_publish = 'YES' order by name");
   }
   if (mysql_num_rows($persons) > 0) {
      print "\n<a name=person></a><h2>" . _("Persons within") . " ".$place['longname']."</h2>\n";
      print $note;
      if ( $privatecount > 0 ) {
        if ( $privatecount > 1 ) {
      	  printf ("\n<br>\n" . _("There are also %d registered persons who do not wish to be listed") . "\n<hr>", $privatecount);
        } else {
          printf ("\n<br>\n" . _("There is also %d registered person who does not wish to be listed") . "\n<hr>", $privatecount);
        }
      }
      page_bar($personcount, $quotedname);
      uindex($personcount, $place, $quotedname);

      if ( $personcount < 20 ) {
	$columns = 1;
      }
      # damn Netscape....must respect margin..
}

print "\n<p>\n<table width=\"95%\">";

      $itemcount = 0;
      while ($sub = mysql_fetch_array($persons)) {
             if ($itemcount++ % $columns == 0) {
     	        print "\n<tr>";
             }
   	     printf("<td width=\"%d%%\">%s",
				50/$columns,
		person_url($sub['f_key'], $sub['name']));
             print "</td>";
	   $home_page = ereg_replace(".*homepage:", "", $sub['f_raw']);
	     if ( $home_page  != $sub['f_raw'] ) {
	    	$home_page = ereg_replace("ident:.*", "", $home_page);
		   if ( ! preg_match("/^http:\/\//", $home_page ) ) {
			$home_page = "http://".$home_page;
		   }
		   printf ("\n<td width=\"%d%%\"><a href=\"%s\" target=\"_blank\">%s</a>", 50/$columns, $home_page, "<img src=\"/gifs/house.png\" alt=\"User homepage logo\" border=\"0\" valign=\"middle\">");
	     } else {
	        printf ("\n<td width=\"%d%%\">", 50/$columns);
	     }
             print "</td></tr>"; 
      }
	print "\n</table>";
   }

print "\n<p>\n";

page_bar($personcount, $quotedname);
pagebottom();
print "\n</body>\n</html>";
?>
